package com.example.indenture.notify;

import com.example.indenture.race.service.RaceService;
import com.example.indenture.race.entity.Race;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

@Component
@RestController
public class RaceNotificationController {
    
    private final List<SseEmitter> emitters = new ArrayList<>();
    
    @Autowired
    private RaceService raceService;

    @GetMapping("/notifications")
    public SseEmitter subscribeNotifications() {
        SseEmitter emitter = new SseEmitter();
        emitters.add(emitter);
        emitter.onCompletion(() -> emitters.remove(emitter));
        return emitter;
    }

    @Scheduled(fixedDelay = 10000) // 每10秒钟执行一次
    public void checkRaceDeadlines() {
        List<Race> races = raceService.getAllRaces();
        System.out.println(races);
        LocalDateTime now = LocalDateTime.now();
        for (Race race : races) {
            LocalDateTime deadline = race.getDeadline();
            long daysRemaining = ChronoUnit.DAYS.between(now, deadline);
            if (daysRemaining < 7) {
                RaceNotification notification = generateNotification(race);
                sendNotification(notification);
            }
        }
    }

    private RaceNotification generateNotification(Race race) {
        RaceNotification notification = new RaceNotification();
        notification.setRaceId((long)race.getCid());
        notification.setRaceName(race.getName());
        // 设置其他通知内容
        return notification;
    }

    private void sendNotification(RaceNotification notification) {
        for (SseEmitter emitter : emitters) {
            try {
                emitter.send(notification, MediaType.APPLICATION_JSON);
            } catch (IOException e) {
                emitter.complete();
            }
        }
    }
}
